#include <iostream>
#include <signal.h>

#include "../common/httplib.h"
using namespace httplib;

#include "./oj_controller.hpp"
using namespace yx;

Controller * con_ptr=nullptr;

void handler(int signo)
{
    con_ptr->recovery();
}

int main()
{
    // 用户请求的服务理由功能
    Server svr;
    
    // 控制器
    Controller con;
    con_ptr=&con;

    signal(SIGINT,handler);

    // 获取所有的题目列表
    svr.Get("/questions_table",[&](const Request &req,Response &resp)
        {
            std::string html;

            con.allQuestions(html);

            resp.set_content(html,"text/html; charset=utf-8");
        });

    // 用户根据题目编号来获取题目内容
    svr.Get(R"(/question/(\d+))",[&](const Request &req,Response &resp)
        {
            std::string number=req.matches[1];
            std::string html;
            
            con.oneQuestion(number,html);

            resp.set_content(html,"text/html; charset=utf-8");
        });

    // 用户提交代码,使用我们的判题功能
    svr.Post(R"(/judge/(\d+))",[&](const Request &req,Response &resp)
        {
            std::string number=req.matches[1];
            std::string out_json;

            con.judge(number,req.body,out_json);
            
            resp.set_content(out_json,"application/json;charset=utf-8");
        });

    svr.set_base_dir("./wwwroot");

    svr.listen("0.0.0.0",9090);

    return 0;
}

// std::string str = "abc123";
// std::vector<std::string> tokens;
// int count = yx::StringUtil::cutString(str, " ", tokens);

// std::cout << "count: " << count << std::endl;
// for (auto &e : tokens)
// {
//     std::cout << e << std::endl;
// }